<?php

namespace App\Console\Commands\Tasks;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class PirateAutoIndependent extends Command
{
    protected $signature = 'task:pirate_auto_independent';
    protected $description = '海盗自动独立池子';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {

        try {
//            Log::info('海盗自动');
            $fromTime   = date('Y-m-d H:i:s', time() - 60);
            $poolConfig = app('model_gashapon_pool_config')->one(['id' => 1]);
            if ($poolConfig['auto_independent_switch'] != 1 || empty($poolConfig['auto_independent_group_ids'])) {
                return null;
            }

            // auto_independent_limit
            //前一分钟 投入大于设定值的用户
            $drawTable = app('model_gashapon_pool_draw')->getTable();
            $userTable = app('model_gashapon_pool_user')->getTable();
            $independentTable = app('model_gashapon_pool_independent')->getTable();
            $autoIndependentUserList = app('model_gashapon_pool_draw')->selectRaw('distinct(' . $drawTable . '.user_id)')
                ->join($userTable, $drawTable . '.user_id', $userTable . '.user_id')
                ->leftJoin($independentTable, $independentTable . '.user_id', $userTable . '.user_id')
                ->where($drawTable . '.created_at', '>=', $fromTime)
                ->whereNull($independentTable.'.user_id')
                ->where($userTable.'.input', '>=', $poolConfig['auto_independent_limit'])->get();

            if ($autoIndependentUserList->isEmpty()) {
                return null;
            }
            $autoIndependentUserIds = explode(',', $poolConfig['auto_independent_group_ids']);
            if (empty($autoIndependentUserIds)) {
                return null;
            }

            $insertIndependentDataList = [];
            //用户插入独立池子列表
            foreach ($autoIndependentUserList as $user) {
                $independentData = [];
                $independentData['user_id']  = $user['user_id'];
                $independentData['group_ids']  = $poolConfig['auto_independent_group_ids'];
                $independentData['remain_group_count']  = count($autoIndependentUserIds);
                $independentData['status']  = 1;
                $insertIndependentDataList[] = $independentData;
            }

            app('model_gashapon_pool_independent')->insert($insertIndependentDataList);

        } catch (\Throwable $exception) {
            Log::error("海盗自动独立池子错误修改 error :" . $exception->getMessage());
        }

    }

}
